package com.md.application.assembler;

import com.md.domain.model.bo.BindRoleBo;
import com.md.domain.model.po.RoleApis;
import com.md.model.po.Apis;
import com.md.model.request.authentication.role.BindRoleApiRequest;
import com.md.util.CollectionUtil;
import com.md.value.enums.AuthEnum;
import lombok.experimental.UtilityClass;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 刘骄阳
 * 2022-12-21 17:35
 */
@UtilityClass
public class RoleApiAssembler {

  /**
   * 构建绑定的响应实体
   *
   * @param roleId  角色id
   * @param apiList apiIdList
   * @return 要入库的api实体
   */
  public static List<RoleApis> buildInsertRoleApi(final Long roleId, final List<Long> apiList) {
    return apiList.stream().map(apiId ->
      RoleApis.builder().roleId(roleId).apiId(apiId).extendsParentRole(false).build()).collect(Collectors.toList());
  }

  /**
   * 构建绑定角色实体
   *
   * @param dbList   数据库的api集合
   * @param request  请求餐胡
   * @param apisList apis集合
   * @return 绑定角色实体
   */
  public static BindRoleBo buildBindRoleBo(final List<RoleApis> dbList,
                                           final BindRoleApiRequest request,
                                           final List<Apis> apisList) {
    BindRoleBo bindRoleBo = new BindRoleBo();
    bindRoleBo.setRoleId(request.getRoleId());
    Map<Long, Integer> map = CollectionUtil.toMap(apisList, Apis::getId, Apis::getAuth);
    List<Long> requestList = request.getApiList();
    List<Long> dbApiIdList = dbList.stream().map(RoleApis::getApiId).collect(Collectors.toList());
    bindRoleBo.setDeleteApiId(dbApiIdList.stream().filter(dbApiId -> !requestList.contains(dbApiId) &&
        map.getOrDefault(dbApiId, AuthEnum.NEED.getCode()).equals(AuthEnum.NEED.getCode())).
      collect(Collectors.toList()));
    bindRoleBo.setInsertApiId(requestList.stream().filter(apisId -> !dbApiIdList.contains(apisId)).collect(Collectors.
      toList()));
    return bindRoleBo;
  }

  public static void buildAndAddRoleApisList(final List<RoleApis> addRoleApisList, final List<Apis> apisList) {
    apisList.forEach(apis -> {
      RoleApis roleApis = new RoleApis();
      roleApis.setApiId(apis.getId());
      roleApis.setExtendsParentRole(false);
      addRoleApisList.add(roleApis);
    });
  }
}
